package com.yikaiye.android.yikaiye.ui.fragment;

import android.annotation.SuppressLint;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.base.BaseFragment;
import com.yikaiye.android.yikaiye.base.BaseViewModel;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.FragmentProductBinding;
import com.yikaiye.android.yikaiye.dialog.AssureDialog;
import com.yikaiye.android.yikaiye.dialog.CallDialog;
import com.yikaiye.android.yikaiye.dialog.ProductFormatDialog;
import com.yikaiye.android.yikaiye.dialog.ZengZhiDialog;
import com.yikaiye.android.yikaiye.http.ApiFactory;
import com.yikaiye.android.yikaiye.model.CheckComboResponseModel;
import com.yikaiye.android.yikaiye.model.CommitOrderModel;
import com.yikaiye.android.yikaiye.model.ProductDetailDataModel;
import com.yikaiye.android.yikaiye.model.ProductServiceModel;
import com.yikaiye.android.yikaiye.ui.activity.home.ConfirmOrderActivity;
import com.yikaiye.android.yikaiye.ui.activity.home.ServiceIntroduceActivity;
import com.yikaiye.android.yikaiye.ui.activity.home.viewmodel.ProductDetailsViewModel;
import com.yikaiye.android.yikaiye.ui.adapter.EmptyRecyclerCommonAdapter;
import com.yikaiye.android.yikaiye.ui.adapter.RecyclerViewHolder;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.UMengUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 产品详情页-产品
 */
public class ProductFragment extends BaseFragment<FragmentProductBinding, BaseViewModel> {

    private List<ProductServiceModel> serviceData = new ArrayList<>();
    private ZengZhiDialog zengZhiDialog;
    private AssureDialog assureDialog;
    private CallDialog callDialog;
    private ProductFormatDialog productFormatDialog;
    private ProductDetailDataModel productDetailDataModel;
    private boolean isLike;
    private String productId;
    private boolean isScrollBottom;

    @Override
    protected ProductDetailsViewModel bindModel() {
        return getViewModel(this, ProductDetailsViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initData() {
        binding.include.tvLinePrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        if (getArguments() != null) {
            productDetailDataModel = getArguments().getParcelable(Constant.DETAIL_MODEL_KEY);
            if (null != productDetailDataModel) {
                if (null != productDetailDataModel.getServiceInfo() && !productDetailDataModel.getServiceInfo().isEmpty()) {
                    serviceData = productDetailDataModel.getServiceInfo();
                    binding.line.setVisibility(serviceData.size() == 1 ? View.GONE : View.VISIBLE);
                } else {
                    binding.rlService.setVisibility(View.GONE);
                }
                binding.include.tvProductName.setText(productDetailDataModel.getTitle());
                binding.include.tvProductDes.setText(productDetailDataModel.getSlogan());
                Glide.with(MyApplication.getContext()).
                        load(ApiFactory.BASE_IMAGE_URL + productDetailDataModel.getPcBanner())
                        .placeholder(R.mipmap.default_image_big).error(R.mipmap.default_image_big).into(binding.ivProductImg);
                productId = productDetailDataModel.getId();
                binding.include.tvLinePrice.setText(mContext.getString(R.string.price, productDetailDataModel.getCostPrice()));
                if (productDetailDataModel.getMinPrice().equals(productDetailDataModel.getMaxPrice())) {
                    binding.include.tvPrice.setText(productDetailDataModel.getMinPrice());
                } else {
                    binding.include.tvPrice.setText(productDetailDataModel.getMinPrice() + "-" + productDetailDataModel.getMaxPrice());
                }
            }
        }
        initDialog();
    }

    @Override
    public void initCtrl() {
        EmptyRecyclerCommonAdapter<ProductServiceModel> serviceAdapter = new EmptyRecyclerCommonAdapter<ProductServiceModel>(getContext(), R.layout.item_product_details_service_layout, serviceData) {
            @Override
            public void convert(RecyclerViewHolder holder, ProductServiceModel item, int position) {
                TextView tvServiceTitle = holder.getView(R.id.tv_service_title);
                tvServiceTitle.setText(item.getName());
                if (position % 2 == 1) {
                    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tvServiceTitle.getLayoutParams();
                    lp.setMargins(60, 0, 0, 0);
                    tvServiceTitle.setLayoutParams(lp);
                }
            }

            @Override
            public void bindClick(RecyclerViewHolder holder, ProductServiceModel item, int position) {
                holder.setOnClickListener(R.id.tv_service_title, view -> {
                    Constant.serviceInstruction = item.getInstruction();
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.NAME_KEY, item.getName());
                    JumpIntent.jump(getActivity(), ServiceIntroduceActivity.class, bundle);
                });
            }
        };
        binding.recyclerView.setAdapter(serviceAdapter);
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.include.llLike, o -> {
            isLike = !isLike;
            binding.include.ivLike.setImageResource(isLike ? R.mipmap.icon_like_sel : R.mipmap.icon_like);
            binding.include.tvLikeStatus.setText(mContext.getString(isLike ? R.string.already_favorite : R.string.favorite));
            if (isLike) {
                UMengUtil.setCountEventId(Constant.PAGE_DETAILS_LIKE);
            }
        });

        viewModel.onDelayClick(binding.llZengZhi, o -> {
            if (null != zengZhiDialog) {
                zengZhiDialog.showDialog();
            }
        });

        viewModel.onDelayClick(binding.llBaoZhang, o -> {
            if (null != assureDialog) {
                assureDialog.showDialog();
            }
        });

        viewModel.onDelayClick(binding.tvCall, o -> {
            if (!XXPermissions.isGrantedPermission(getContext(), Permission.CALL_PHONE)) {
                XXPermissions.with(this)
                        .permission(Permission.CALL_PHONE)
                        .request((permissions, all) -> {
                            if (null != callDialog) {
                                callDialog.showDialog();
                            }
                        });
            } else {
                if (null != callDialog) {
                    callDialog.showDialog();
                }
            }
            UMengUtil.setCountEventId(Constant.PAGE_DETAILS_CONTACT_SERVICE);
        });

        viewModel.onDelayClick(binding.tvBug, o -> {
            if (null != productFormatDialog) {
                productFormatDialog.showDialog();
            }
            UMengUtil.setCountEventId(Constant.PAGE_DETAILS_ORDER);
        });
    }

    private void initDialog() {
        zengZhiDialog = new ZengZhiDialog(mContext);
        assureDialog = new AssureDialog(mContext);
        callDialog = new CallDialog(mContext);
        productFormatDialog = new ProductFormatDialog(mContext, serviceData, productId) {
            @Override
            public void confirmOrder(CheckComboResponseModel checkComboResponseModel) {
                UMengUtil.setCountEventId(Constant.DIALOG_ATTR_BUY);
                Log.e("@@@@@@@@1", new Gson().toJson(checkComboResponseModel));
                if (null != productDetailDataModel) {
                    CommitOrderModel commitOrderModel = new CommitOrderModel();
                    commitOrderModel.setProductId(productId);
                    commitOrderModel.setProductName(productDetailDataModel.getTitle());
                    commitOrderModel.setPrice(checkComboResponseModel.getProductPrice());
                    // android传2
                    commitOrderModel.setPlatform(2);
                    // 订单类型：2=预订单
                    commitOrderModel.setType(2);
                    commitOrderModel.setStatus(0);
                    commitOrderModel.setVersion("1");
                    commitOrderModel.setSource(0);

                    for (CheckComboResponseModel.ServiceAttrModel serviceAttrModel : checkComboResponseModel.getProductServiceAttrLists()) {
                        CommitOrderModel.Item item = new CommitOrderModel.Item();
                        item.setServiceId(serviceAttrModel.getServiceId());
                        item.setSelectInfo(serviceAttrModel.getTerminalName());
                        item.setSelectInfoId(serviceAttrModel.getAttrListId());
                        item.setServiceName(serviceAttrModel.getServiceName());
                        item.setPrice(serviceAttrModel.getServiceAttrPrice());
                        item.setBookPeriod(serviceAttrModel.getServiceAttrCycle());
                        item.setProductAttrListId(serviceAttrModel.getId());

                        item.setServiceType(serviceAttrModel.getServiceType());
                        item.setServiceAttrCycleType(serviceAttrModel.getServiceAttrCycleType());
                        item.setTerminalName(serviceAttrModel.getTerminalName());
                        commitOrderModel.getItems().add(item);
                    }
                    Log.e("@@@@@@@@@@2", new Gson().toJson(commitOrderModel));
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.DES_KEY, productDetailDataModel.getSlogan());
                    bundle.putString(Constant.IMG_KEY, productDetailDataModel.getPcBanner());
                    bundle.putSerializable(Constant.MODEL_KEY, commitOrderModel);
                    JumpIntent.jump(getActivity(), ConfirmOrderActivity.class, bundle);
                }
            }
        };
    }

    public static ProductFragment newInstance(ProductDetailDataModel productDetailDataModel) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constant.DETAIL_MODEL_KEY, productDetailDataModel);
        ProductFragment fragment = new ProductFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if (isVisibleToUser) {
//            binding.scrollView.post(() -> binding.scrollView.scrollTo(0, 0));
//        }
//    }
}
